package com.xgr.wonderful.fragment;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.handmark.pulltorefresh.library.ILoadingLayout;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener2;
import com.xgr.wonderful.R;
import com.xgr.wonderful.activity.CommentActivity;
import com.xgr.wonderful.activity.base.BaseFragment;
import com.xgr.wonderful.adapter.StatusContentAdapter;
import com.xgr.wonderful.constant.Constant;
import com.xgr.wonderful.entity.Status;
import com.xgr.wonderful.utils.HttpProxy;
import com.xgr.wonderful.utils.LocalUserUtils;
import com.xgr.wonderful.utils.ToastFactory;
import com.xgr.wonderful.utils.HttpProxy.IHttpRequestListener;

public class RepliedFragment extends BaseFragment {
	private ArrayList<Status> mStatusList = new ArrayList<Status>();
	private StatusContentAdapter mStatusAdapter;

	private View contentView;
	private PullToRefreshListView mPullRefreshListView;
	private ListView actualListView;
	private TextView networkTips;
	private ProgressBar progressbar;
	private int clickIndex = -1;

	public enum RefreshType {
		REFRESH, LOAD_MORE
	}
	private RefreshType mRefreshType = RefreshType.REFRESH;
	private int lastStatusId = -1;
	
	private HttpProxy httpProxy;

	@Override
	public void onAttach(Activity activity) {
		// TODO Auto-generated method stub
		super.onAttach(activity);
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub

		contentView = inflater.inflate(R.layout.fragment_statuscontent, null);
		mPullRefreshListView = (PullToRefreshListView) contentView
				.findViewById(R.id.pull_refresh_list);
		networkTips = (TextView) contentView.findViewById(R.id.networkTips);
		progressbar = (ProgressBar) contentView.findViewById(R.id.progressBar);
		
		mPullRefreshListView.setMode(Mode.BOTH);
		// 设置上下拉时的显示文字 ,还可以设置图片
		ILoadingLayout startLabels = mPullRefreshListView
				.getLoadingLayoutProxy(true, false);
		startLabels.setPullLabel("下拉刷新...");// 刚下拉时，显示的提示
		startLabels.setRefreshingLabel("正在载入...");// 刷新时
		startLabels.setReleaseLabel("放开刷新...");// 下来达到一定距离时，显示的提示

		ILoadingLayout endLabels = mPullRefreshListView.getLoadingLayoutProxy(
				false, true);
		endLabels.setPullLabel("上拉刷新...");// 刚下拉时，显示的提示
		endLabels.setRefreshingLabel("正在载入...");// 刷新时
		endLabels.setReleaseLabel("放开刷新...");// 下来达到一定距离时，显示的提示
		mPullRefreshListView
				.setOnRefreshListener(new OnRefreshListener2<ListView>() {

					@Override
					// 下拉事件
					public void onPullDownToRefresh(
							PullToRefreshBase<ListView> refreshView) {
						mPullRefreshListView.setMode(Mode.BOTH);
						mRefreshType = RefreshType.REFRESH;
						fetchData();
					}

					@Override
					// 上拉事件
					public void onPullUpToRefresh(
							PullToRefreshBase<ListView> refreshView) {
						mPullRefreshListView.setMode(Mode.BOTH);
						mRefreshType = RefreshType.LOAD_MORE;
						fetchData();
					}
				});

		actualListView = mPullRefreshListView.getRefreshableView();
		mStatusAdapter = new StatusContentAdapter(mContext, mStatusList);
		actualListView.setAdapter(mStatusAdapter);
		// 对于用户回复过的状态列表，优先使用本地缓存的列表
		//List<Status> list = Cache.getUserRepliedStatus();
//		if (list != null) {
//			mStatusList.addAll(list);
//		}
		// 如果本地没有缓存，则从服务器获取
		if (mStatusList.size() == 0) {
			fetchData();
		} else {
			lastStatusId = mStatusList.get(mStatusList.size() - 1).getId();
			setState(LOADING_COMPLETED);
			mStatusAdapter.notifyDataSetChanged();
		}
		actualListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				// TODO Auto-generated method stub
				clickIndex = position - 1;
				Intent intent = new Intent();
				intent.setClass(getActivity(), CommentActivity.class);
				intent.putExtra("data", mStatusList.get(clickIndex));
				startActivityForResult(intent, Constant.REQUEST_CODE_COMMENT_NUM);
			}
		});
		return contentView;
	}

	@Override
	public void onDetach() {
		// TODO Auto-generated method stub
		super.onDetach();
//		Cache.putUserRepliedStatus(new Gson().toJson(mStatusList));
	}
	
	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == Activity.RESULT_OK) {
			switch (requestCode) {
			case Constant.REQUEST_CODE_COMMENT_NUM: //评论后增加
				int commentInc = data.getIntExtra(
						Constant.COMMENT_NUM_INCREAMENT, 0);
				if (commentInc != 0) {
					mStatusList.get(clickIndex).increaseCommentnum(commentInc);
					mStatusAdapter.notifyDataSetChanged();
				}
				break;
			default:
				break;
			}
		}
	}
	
	public void fetchData() {
		Status status = null;
		String statusJson = null;
		if (mRefreshType == RefreshType.REFRESH) {
			status = new Status(LocalUserUtils.getInstance().getLocalUserID(),
					Integer.valueOf(0), Constant.NUMBERS_PER_PAGE,
					null, null, null);
		} else {
			status = new Status(LocalUserUtils.getInstance().getLocalUserID(),
					lastStatusId, Constant.NUMBERS_PER_PAGE,
					null, null, null);
		}
		try {
			statusJson = new Gson().toJson(status);
		} catch (Exception e) {
			e.printStackTrace();
		}
		if (statusJson != null) {
			HttpProxy httpProxy = new HttpProxy();
			httpProxy.queryCommentedStatus( statusJson, new IHttpRequestListener() {

				@Override
				public void OnHttpRequestSuccessful(String result, int errCode) {
					// TODO Auto-generated method stub
					handleData(result, errCode);
				}

				@Override
				public void OnHttpRequestStart() {
					setState(LOADING) ;
				}

				@Override
				public void OnHttpRequestFailure(String info) {
					ToastFactory.getToast(mContext, "更新数据失败，请检查网络环境后重试").show();
					setState(LOADING_FAILED);
					mPullRefreshListView.onRefreshComplete();
				}
			});
		}
	}

	private static final int LOADING = 1;
	private static final int LOADING_COMPLETED = 2;
	private static final int LOADING_FAILED = 3;
	private static final int LOADING_NO_MORE_DATA = 4;

	public void setState(int state) {
		switch (state) {
		case LOADING:
			if (mStatusList == null || mStatusList.size() == 0) {
				networkTips.setVisibility(View.GONE);
				progressbar.setVisibility(View.VISIBLE);
			}
			break;
		case LOADING_COMPLETED:
			networkTips.setVisibility(View.GONE);
			progressbar.setVisibility(View.GONE);
			mPullRefreshListView.setVisibility(View.VISIBLE);
			break;
		case LOADING_FAILED:
			if (mStatusList == null || mStatusList.size() == 0) {
				networkTips.setVisibility(View.VISIBLE);
			}
			mPullRefreshListView.setVisibility(View.VISIBLE);
			progressbar.setVisibility(View.GONE);
			break;
		case LOADING_NO_MORE_DATA:
			networkTips.setVisibility(View.GONE);
			mPullRefreshListView.setVisibility(View.VISIBLE);
			progressbar.setVisibility(View.GONE);
			break;
		default:
			break;
		}
	}
	

	private void handleData(String result, int errCode) {
		List<Status> queryList = null;
		if (errCode == Constant.ERR_HTTP_REQUEST_SUCCESS) {
			try {
				queryList = new Gson().fromJson(result,
						new TypeToken<List<Status>>() {
						}.getType());
			} catch (Exception e) {
				e.printStackTrace();
			}
			if (queryList != null && queryList.size() != 0) {
				if (mRefreshType == RefreshType.REFRESH) {
					mStatusList.clear();
				}
				if (queryList.size() < Constant.NUMBERS_PER_PAGE) {
					ToastFactory.getToast(mContext, "没有更多数据了").show();
				}
				mStatusList.addAll(queryList);
				lastStatusId = mStatusList.get(mStatusList.size() - 1).getId();
				mStatusAdapter.notifyDataSetChanged();
			} else if (queryList != null && queryList.size() == 0) {
				if (lastStatusId > 0) {
					// 说明 有status且不是第一次拉取，然后没有数据了
					ToastFactory.getToast(mContext, "没有更多数据了").show();
				} else {
					// 本来就没有评论，所以为0， 不用显示
					ToastFactory.getToast(mContext, "暂时还没有数据").show();
				}
			}
			setState(LOADING_COMPLETED);
			mPullRefreshListView.onRefreshComplete();
		} else if (errCode == Constant.ERR_HTTP_REQUEST_FAILURE) {
			ToastFactory.getToast(mContext, "加载数据失败").show();
			setState(LOADING_FAILED);
			mPullRefreshListView.onRefreshComplete();
		}
	}

}
